use std::collections::HashMap;


/**
 * 做单元测试用
*/


pub async fn init_app_test_one(configuration: Option<crate::WebConfig>, sub_path: &str, sub_router: axum::Router) -> axum::Router
{
    let mut map = HashMap::<&str, axum::Router>::new();
    map.insert(sub_path, sub_router);
    init_app_test(configuration, map).await
}

/// 单元测试用
pub async fn init_app_test(configuration: Option<crate::WebConfig>, router_map: HashMap<&str, axum::Router>) -> axum::Router
{
    let configuration = &if configuration.is_none() {
        crate::read_web_configuration("./web.toml")
    } else { configuration.unwrap() };

    if let Some(value) = &configuration.locale {
        rust_i18n::set_locale(value);
    }

    if let Some(value) = &configuration.dev {
        let db_url = crate::deal_db_url(&value.db);
        crate::db::init_rbatis(&db_url);
    } else { panic!("database connect error") }


    let session_layer = crate::init_session_layer().await;
    let mut router = axum::Router::new();
    for (k, v) in router_map {
        router = router.nest(&k, v);
    }
    router.layer(session_layer)
}


/// 单元测试用
pub fn start_server_test(router: axum::Router) -> axum_test::TestServer
{
    axum_test::TestServer::new(router.into_make_service())
        .expect("test server init error")
}


pub async fn get(router: axum::Router, path: &str) -> axum_test::TestResponse
{
    let server = start_server_test(router);
    server.get(path)
        .await
}


pub async fn post(router: axum::Router, path: &str) -> axum_test::TestRequest
{
    let server = start_server_test(router);
    server.post(path)
}

pub async fn post_text<T>(router: axum::Router, path: &str, text: T) -> axum_test::TestResponse
    where T: std::fmt::Display
{
    let server = start_server_test(router);
    server.post(path)
        .text(text)
        .await
}

pub async fn post_json<J>(router: axum::Router, path: &str, body: &J) -> axum_test::TestResponse
        where J: serde::Serialize
{
    let server = start_server_test(router);
    server.post(path)
        .json(body)
        .await
}



